package com.zxq.modbus.dispatch;


import com.sun.org.apache.xerces.internal.impl.dv.util.HexBin;

import com.zxq.exchange.model.ExchangeDTO;
import com.zxq.exchange.register.INotifyDevice;
import com.zxq.exchange.register.INotifyPlatform;
import com.zxq.exchange.register.NotifyPlatformRegister;
import com.zxq.modbus.config.ModbusConfig;
import com.zxq.modbus.utils.ModBusCrc;
import com.zxq.modbus.container.LockContainer;
import com.zxq.modbus.container.ModBusChannelContainer;
import com.zxq.tcp.handler.dispatch.HandlerDispatch;
import lombok.extern.slf4j.Slf4j;
import net.sf.jsqlparser.statement.execute.Execute;

@Slf4j
public class ModBusHandler extends HandlerDispatch  {


    public ModBusHandler() {

    }


    @Override
    public void decodeFrame() {
               ModBusCrc modBusCrc =  ModBusChannelContainer.getModbusCrc(channel);
               int length =  modBusCrc.measureFrameLen();
               if (in.readableBytes() < length) {
                    //log.info("当前可读数据不够，继续等待4。。");
                    return ;
                }
                byte[] content = new byte[length];

                in.readBytes(content);
                //解锁发送数据
                boolean isLegal = modBusCrc.isLegalFrame(content);
                if(!isLegal) {
                    log.info("channel:" + channel.toString() + " error:" +HexBin.encode(content));
                    return;
                }
                //解析后的欣喜，发送给平台
                ExchangeDTO exchangeDTO = new ExchangeDTO();
                exchangeDTO.setProtocolId(ModbusConfig.getProtocolId());
                exchangeDTO.setCmd_id(HexBin.encode(new byte[]{content[0]}));
                exchangeDTO.setDevId(ModBusChannelContainer.getChannelKey(channel));
                exchangeDTO.setData(content);

                NotifyPlatformRegister.getInstance().notifyMessage(exchangeDTO);
    }

    @Override
    public boolean isThisFrame() {

         byte primaryByte = in.readByte();
         byte secondByte = in.readByte();
        // log.info("hex:" + HexBin.encode(new byte[]{primaryByte,secondByte}));
         in.resetReaderIndex();
         ModBusCrc modBusCrc = ModBusChannelContainer.getModbusCrc(channel);
         if(modBusCrc == null)
             return false;
         return modBusCrc.isModelBus(primaryByte,secondByte);
    }





}
